<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" title="入库" :visible.sync="visible" width="950px"
             :before-close="onCancel">
    <el-form ref="form" :model="form" label-width="auto" :rules="rules">
      <el-form-item label="入库仓库：" prop="warehouse_id">
        <WarehouseSelect :astrict="1" v-model="form.warehouse_id" placeholder="请选择入库仓库"/>
      </el-form-item>
      <el-form-item label="入库类型：" prop="type">
        <el-select v-model="form.type" placeholder="请选择入库类型">
          <el-option v-for="(item, index) in typeList" :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="备注：" prop="description">
        <el-input v-model="form.description" placeholder="请输入备注" type="textarea" :rows="5"/>
      </el-form-item>
      <editTable :table.sync="form.part_categories" url="part_categories" ref="editTableRef"></editTable>
    </el-form>
    <div slot="footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="onSave('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import editTable from "./EditTable.vue";
import WarehouseSelect from "@/views/bom/stock/components/WarehouseSelect.vue";

export default {
  components: {WarehouseSelect, editTable},
  props: {
    typeList: Array
  },
  data() {
    return {
      // 弹窗是否打开
      visible: false,
      loading: false,
      // 表单数据
      form: {
        description: null,
        type: null,
        warehouse_id: null,
        part_categories: [
          {}
        ],
      },
      rules: {
        type: [
          {required: true, message: '请选择入库类型', trigger: 'change'},
        ],
        warehouse_id: [
          {required: true, message: '请选择入库仓库', trigger: 'change'},
        ],
      },
      warehouseOptions: [],
    }
  },
  methods: {
    active() {
      this.visible = true;
    },
    onCancel() {
      this.$refs.form.resetFields();
      this.visible = false;
    },
    /*提交*/
    onSave(formName) {
      let flag = false, flag2 = false
      this.$refs[formName].validate(valid => flag = valid);
      flag2 = this.$refs.editTableRef.validate()
      if (flag && flag2) {
        const form = JSON.parse(JSON.stringify(this.form))
        form.part_categories = form.part_categories.map(({id, quantity}) => ({id, quantity}))
        this.handlePostForm(form)
      }
    },
    async handlePostForm(form) {
      const res = (await this.$http.post('/inventories/batch_storage', form)).data
      res.success ? this.$message.success(res.msg) : this.$message.error(res.msg)
      this.$emit('reload')
      this.onCancel()
    },
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}

</style>
